#include "switch.h"
#include "socket.h"
#include "stdio.h"
#include "string.h"
#include "pthread.h"

char itoc(int num )
{
    if( num < 0x0a )
    {
        return num + '0';
    }
    
    return num - 0x0a + 'A';
}

static void CPUID_Get(char *buf)
{
    char *Point = (char *)0x1FFFF7E8;
    int i;
	
    for( i = 0; i < 12; i++ ){
        buf[2 * i] = itoc( Point[i] & 0x0f );
        buf[2 * i + 1] = itoc( Point[i]  >> 4 );
    }
    buf[2 * i] = '\0';    
}

void switch_thread_entry(void *param)
{
    int sockfd;
    struct sockaddr sockaddr;

    if ((sockfd = socket(AF_INET, SOCK_PACKET, 0)) == 0)
    {
        printf("init socket error.\r\n");
    }
    
    sockaddr.sin_port = 10001;
    sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);   
    bind(sockfd, &sockaddr, 1);
    
    sockaddr.sin_port = 10000;
    sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    connect(sockfd, &sockaddr, 1);
    
    while(1)
    {
        char send_buf[128];
        char cpu_id[32];   
        const char *act_msg = "{\"msg\":\"activate\",\"cpuid\":\"%s\"}";
        int len;
    
        CPUID_Get(cpu_id);
        len = sprintf(send_buf, act_msg, cpu_id);
        if (write(sockfd, send_buf, len) > 0)
        {
            printf("send successfully.\r\n");
        }
    }
}